from django.shortcuts import render

# Create your views here.
from django.http import HttpResponse
import requests
import time
from bs4 import BeautifulSoup
import re
import json
import urllib


#返回结果格式
def resultData():
    data = {
        "websiteType" : 0,
        "titleName":"",
        "titleHref": "",
        "source":"",
        "label":"",
        "volume":"",
        "summary":"",
        "detailId":'',
        "publishTime" :"",
        "category" : "",
        "quote" :"",
        "abstract": "",
        "doi": "",
        "downLoad": "",
        "keyword": [],
        "author": [],

    }
    return data

def formData(response):

    lis = response.json()["ListArticle"]

    allData = []

    for li in lis:
        tempData = resultData()
        try:
            tempData["titleName"] = li["Title"]
        except:
            pass

        try:
            tempData["titleHref"] = "http://ipub.exuezhe.com/paper.html?id={}".format(li["Id"])
        except:
            pass

        try:
            tempData["author"] = li["Author"].split("/")
        except:
            pass

        try:
            tempData["abstract"] = li["Abstracts"]
        except:
            pass

        try:
            tempData["keyword"] = [li["KeyWords"]]
        except:
            pass



        allData.append(tempData)

    return allData

def getData(keyword):

    headers = {
        'Origin': 'http://ipub.exuezhe.com',
        'Accept-Encoding': 'gzip, deflate',
        'Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8',
        'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36',
        'Proxy-Authorization': 'Basic cWY6cWYzLjE0MTU=',
        'Content-Type': 'application/x-www-form-urlencoded',
        'Accept': '*/*',
        'Referer': 'http://ipub.exuezhe.com/qw.html?s0=0&s1=cell',
        'X-Requested-With': 'XMLHttpRequest',
        'Proxy-Connection': 'keep-alive',
    }

    strr = '{"TreeCode":"01,02,03,04,05,06,07,08,09","StartYear":"1995","EndYear":"2018","ListSearchCondition":[{"Type":"0","KeyWord":"' + keyword + '","RelationShip":"1"}],"Order":"1","PageSize":20,"PageIndex":1,"IsBuy":0}'

    data = {
        'data': strr
    }

    response = requests.post('http://ipub.exuezhe.com/Qw/Search', headers=headers, data=data)

    allData = formData(response)


    return allData


def index(request):

    data = json.loads(request.POST.get('data', '1'))

    # cookies = getOnoCookies()
    allData = getData(data["values"][0])

    return HttpResponse(json.dumps({
        "collection": allData,
        "allNum": 0
    }), content_type="application/json")